package com.tax.manager;

import com.tax.config.jwt.JwtTokenUtil;
import com.tax.config.jwt.JwtUserInfo;
import com.tax.entity.TdUser;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import java.util.concurrent.TimeUnit;

/**
 * @ClassName AccessTokenManager
 * @Author duandehui
 * @DATE 2023-03-04
 * @Version 1.0
 **/
@Component("accessTokenManager")
public class AccessTokenManager {

    private static Logger log = LoggerFactory.getLogger(AccessTokenManager.class);

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private RedisApiManager redisApiManager;

    public String generateToken(TdUser tblUser,
                                String deviceId,
                                String appsys,
                                String appVersion) {
        Assert.notNull(tblUser,"centerUser must not be null");
        JwtUserInfo jwtUserInfo=new JwtUserInfo();
        jwtUserInfo.setUserId(tblUser.getUserId());
        jwtUserInfo.setTelephone(tblUser.getTelephone());
        jwtUserInfo.setDeviceId(deviceId);
        jwtUserInfo.setAppSys(appsys);
        jwtUserInfo.setAppVersion(appVersion);
        jwtUserInfo.setUserLoginType(tblUser.getUserLoginType());
        return jwtTokenUtil.generateToken(jwtUserInfo);
    }


    public JwtUserInfo getJwtUserInfo(String accessToken) {
        return jwtTokenUtil.getJwtUserInfo(accessToken);
    }

    public void cacheLoginToken(String phoneNum, String generateToken) {
        try{
            if(StringUtils.isNotBlank(phoneNum)&&StringUtils.isNotBlank(generateToken)){
                redisApiManager.set("tax:phoneNum:"+phoneNum,generateToken,7,TimeUnit.DAYS);
            }
        }catch (Exception e){
            log.error("cacheLoginToken err",ExceptionUtils.getStackTrace(e));
        }
    }
}
